const fs = require('fs');
const path = require('path');
const config = require('../config');

// 系统配置文件
const SYSTEM_CONFIG_FILE = path.join(__dirname, '../data/system_config.json');
// API密钥配置文件
const API_KEYS_FILE = path.join(__dirname, '../data/api_keys.json');

// 确保数据目录存在
const ensureDataDirExists = () => {
  const dataDir = path.join(__dirname, '../data');
  if (!fs.existsSync(dataDir)) {
    fs.mkdirSync(dataDir);
  }
};

// 初始化系统配置
const initSystemConfig = () => {
  ensureDataDirExists();
  if (!fs.existsSync(SYSTEM_CONFIG_FILE)) {
    const defaultConfig = {
      appName: 'CryptoTrader',
      version: '1.0.0',
      backtest: {
        defaultInitialBalance: 10000,
        defaultFeeRate: 0.001
      },
      trading: {
        maxPositionSize: 10000,
        defaultSlippage: 0.001
      }
    };
    fs.writeFileSync(SYSTEM_CONFIG_FILE, JSON.stringify(defaultConfig, null, 2));
  }
};

// 初始化API密钥配置
const initApiKeys = () => {
  ensureDataDirExists();
  if (!fs.existsSync(API_KEYS_FILE)) {
    const defaultKeys = {
      binance: {
        apiKey: '',
        apiSecret: ''
      }
    };
    fs.writeFileSync(API_KEYS_FILE, JSON.stringify(defaultKeys, null, 2));
  }
};

// 获取系统配置
exports.getConfig = () => {
  initSystemConfig();
  return JSON.parse(fs.readFileSync(SYSTEM_CONFIG_FILE, 'utf8'));
};

// 更新系统配置
exports.updateConfig = (newConfig) => {
  initSystemConfig();
  const currentConfig = exports.getConfig();
  const updatedConfig = {
    ...currentConfig,
    ...newConfig
  };
  fs.writeFileSync(SYSTEM_CONFIG_FILE, JSON.stringify(updatedConfig, null, 2));
  return updatedConfig;
};

// 获取API密钥配置
exports.getApiKeys = () => {
  initApiKeys();
  const apiKeys = JSON.parse(fs.readFileSync(API_KEYS_FILE, 'utf8'));
  // 不返回完整的密钥信息，只返回密钥是否已设置的状态
  return {
    binance: {
      hasApiKey: !!apiKeys.binance.apiKey,
      hasApiSecret: !!apiKeys.binance.apiSecret
    }
  };
};

// 更新API密钥配置
exports.updateApiKeys = (newApiKeys) => {
  initApiKeys();
  const currentApiKeys = JSON.parse(fs.readFileSync(API_KEYS_FILE, 'utf8'));
  const updatedApiKeys = {
    ...currentApiKeys,
    ...newApiKeys
  };
  fs.writeFileSync(API_KEYS_FILE, JSON.stringify(updatedApiKeys, null, 2));
  return updatedApiKeys;
};

// 获取完整API密钥（仅供内部服务使用）
exports.getFullApiKeys = () => {
  initApiKeys();
  return JSON.parse(fs.readFileSync(API_KEYS_FILE, 'utf8'));
};